package org.openscheduler.modules.scheduler;

import java.io.IOException;

import javax.servlet.http.HttpSession;

import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;

/**
 * TODO : factory 에서  scheduler 를 가져 올 수 있으나
 * 설정 프로퍼티는 가져올 수 없다. 따로 보관하도록 해야 한다.
 * 
 * @author allbegray
 *
 */

@Controller
@RequestMapping("/scheduler")
public class SchedulerController {
	
	@Autowired
	SchedulerValidator schedulerValidator;
	
	@Autowired
	SchedulerService schedulerService;
	
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Model model) throws SchedulerException {
		model.addAttribute("schedulers", schedulerService.getAllSchedulerMetaDataWrappers());
		return "scheduler/list";
	}
	
	@RequestMapping(value = "/{schedName}", method = RequestMethod.GET)
	public String view(@PathVariable String schedName, Model model) throws SchedulerException {
		model.addAttribute("scheduler", schedulerService.getSchedulerWrapper(schedName));
		return "scheduler/view";
	}
	
	@RequestMapping(value = "/{schedName}/pauseAll", method = RequestMethod.GET)
	public String pauseAll(@PathVariable String schedName) throws SchedulerException {
		schedulerService.pauseAll(schedName);
		return "redirect:/scheduler/" + schedName;
	}
	
	@RequestMapping(value = "/{schedName}/resumeAll", method = RequestMethod.GET)
	public String resumeAll(@PathVariable String schedName) throws SchedulerException {
		schedulerService.resumeAll(schedName);
		return "redirect:/scheduler/" + schedName;
	}
	
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String createForm(Model model) {
		return "scheduler/create";
	}
	
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String create(@RequestParam("configProps") String props, Model model) throws SchedulerException, IOException {
//	public String create(@RequestParam("configPropsText") String configPropsText, BindingResult result, SessionStatus status, HttpSession session, Model model) throws SchedulerException, IOException {
//		schedulerValidator.validate(configPropsText, result);
//		if (result.hasErrors()) {
//			return "scheduler/create";
//		} else {
			String schedName = schedulerService.createScheduler(props);
//			status.setComplete();
			return "redirect:/scheduler/" + schedName;
//		}
	}
	
}
